package cn.hinglo.website.config.interceptors;

import cn.hinglo.baseservice.annotation.IgnoreToken;
import cn.hinglo.baseservice.interceptors.BaseLoginInterceptor;
import cn.hinglo.common.constant.SystemConstant;
import cn.hinglo.common.enums.ExceptionEnum;
import cn.hinglo.common.utils.ResultUtils;
import cn.hinglo.website.bean.model.User;
import cn.hinglo.website.config.constant.SysConstant;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * @createTime: 2018/11/5 15:16
 * @author: HingLo
 * @description: 登录认证拦截器, 及配置自己过滤规则
 */
public class LoginInterceptor extends BaseLoginInterceptor {

    @Override
    public void ignoreAnnotationUrlList() {
        annotationList.add(IgnoreToken.class);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler, HandlerMethod handlerMethod)
            throws Exception {
        // 自定义实现的登录权限拦截器
        User user = (User) request.getSession().getAttribute(SysConstant.LOGIN);
        if (user == null) {
            ResultUtils.error(response, ExceptionEnum.TOKENINVALID);
            return false;
        }
        Map<String, Object> msg = new HashMap<>(1);
        msg.put(SystemConstant.PERMISSION_USER_ID, user.getId());
        success(request, response, msg);
        return true;
    }

    @Override
    public void success(HttpServletRequest request, HttpServletResponse response, Map<String, Object> msg) {
        msg.forEach(request::setAttribute);
    }

}
